package easy;

import java.util.Arrays;
import java.util.HashMap;

/**
 * 第一次做LeetCode算法题
 * <p>
 * 题目：给予一组整数和一个目标整数，从数组中找到两个数，其和为目标整数，返回该两个整数对应的下标
 * 假设每次输入仅有一个解，两个数的下标不一样
 * <p>
 * 例如：nums = [2, 7, 11, 15], target = 9
 * 返回：[0, 1]
 * <p>
 *
 * @author zj
 * @date 2018/07/30
 * @see <a href="https://leetcode.com/problems/two-sum/description/">题目</a>
 * @see <a href="https://leetcode.com/articles/two-sum/">解答</a>
 */
public class TwoSum {
    /**
     * 暴力解法
     * 重复遍历数组，匹配两个数之和是否等于目标整数
     * 时间复杂度：O(n^2)
     * 控件复杂度: O(1)
     */
    private int[] twoSum(int[] nums, int target) {
        for (int i = 0; i < nums.length - 1; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                if ((nums[i] + nums[j]) == target) {
                    return new int[]{i, j};
                }
            }
        }
        throw new IllegalArgumentException("No two sum solution");
    }

    /**
     * 利用HashMap保存数值值和对应的下标，遍历数组，如果存在两个值相加等于目标整数而且其下标不一致，返回结果
     * 时间复杂度：O(n) - for循环需要O(n)，HashMap的put/containsKey操作的平均时间复杂度为O(1)
     * 空间复杂度：O(n) - 包含一个额外的HashMap
     */
    public int[] twoSum2(int[] nums, int target) {
        HashMap<Integer, Integer> map = new HashMap<>(16);
        for (int i = 0; i < nums.length; i++) {
            map.put(nums[i], i);
        }
        for (int i = 0; i < nums.length; i++) {
            int remain = target - nums[i];
            if (map.containsKey(remain) && map.get(remain) != i) {
                return new int[]{i, map.get(remain)};
            }
        }
        throw new IllegalArgumentException("No two sum solution");
    }

    /**
     * 将方法2中的两个for循环并在一起
     * Note：此时remain对应的键一定在当前下标之前
     */
    public int[] twoSum3(int[] nums, int target) {
        HashMap<Integer, Integer> map = new HashMap<>(16);
        for (int i = 0; i < nums.length; i++) {
            int remain = target - nums[i];
            if (map.containsKey(remain) && map.get(remain) != i) {
                return new int[]{map.get(remain), i};
            }
            map.put(nums[i], i);
        }
        throw new IllegalArgumentException("No two sum solution");
    }

    public static void main(String[] args) {
        int[] nums = new int[]{2, 7, 11, 15};
        int target = 9;
        int[] res = new TwoSum().twoSum(nums, target);
        System.out.println(Arrays.toString(res));
    }

}
